package com.aaa.os.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @FileName: RabbitMQConfig
 * @Description:
 * @Author: CH
 * @CreateTime: 2025/10/17 11:33
 * @Version: 1.0.0
 */
@Configuration
public class RabbitMQConfig {
    //死信交换机 (用于处理已经过期的消息)
    public static final String DEAD_LETTER_EXCHANGE = "order_dead_letter_exchange";
    //死信队列
    public static final String DEAD_LETTER_QUEUE = "order_dead_letter_queue";
    //死信路由键
    public static final String DEAD_LETTER_ROUTING_KEY = "order.dead";
    //延迟交换机 (用于暂存等待超时的消息)
    public static final String DELAY_EXCHANGE = "order_delay_exchange";
    // 延迟队列
    public static final String DELAY_QUEUE = "order_delay_queue";
    //延迟路由键
    public static final String DELAY_ROUTING_KEY = "order.delay";

    //配置死信交换机
    //DirectExchange 直接交换机，适合点对点的精确路由
    @Bean
    public DirectExchange deadLetterExchange(){
        return ExchangeBuilder.directExchange(DEAD_LETTER_EXCHANGE).durable(true).build();
    }

    //配置死信队列
    @Bean
    public Queue deadLetterQueue(){
        return QueueBuilder.durable(DEAD_LETTER_QUEUE).build();
    }

    //绑定死信队列和死信交换机
    @Bean
    public Binding deadLetterBinding(){
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with(DEAD_LETTER_ROUTING_KEY);
    }

    //配置延迟交换机
    @Bean
    public DirectExchange delayExchange(){
        return ExchangeBuilder.directExchange(DELAY_EXCHANGE).durable(true).build();
    }

    //配置延迟队列
    @Bean
    public Queue delayQueue(){
        //定义Map
        Map<String,Object> delayQueueArgsMap = new HashMap();
        //配置参数
        //让当前队列和死信交换机进行绑定
        delayQueueArgsMap.put("x-dead-letter-exchange",DEAD_LETTER_EXCHANGE);
        //让当前队列和死信路由键进行绑定
        delayQueueArgsMap.put("x-dead-letter-routing-key",DEAD_LETTER_ROUTING_KEY);
        //配置参数，让当前队列设置消息的过期时间
        // x-message-ttl 消息的过期时间  ttl=time to live 生存时间（过期时间） 单位是毫秒
        //1*60*1000=1分钟
        delayQueueArgsMap.put("x-message-ttl",1*60*1000);
        //使用QueueBuilder提供build创建队列
        return QueueBuilder.durable(DELAY_QUEUE).withArguments(delayQueueArgsMap).build();
    }

    //绑定延迟队列和延迟交换机
    @Bean
    public Binding delayBinding(){
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(DELAY_ROUTING_KEY);
    }


}
